package com.stanyung.realtimeserver.codec;

public class ByteUtil {
	
	public static byte[] int2Bytes(int x) {
		byte[] buff = new byte[4];
		buff[0] = (byte) (x >> 24);
		buff[1] = (byte) (x >> 16);
		buff[2] = (byte) (x >> 8);
		buff[3] = (byte) x;
		return buff;
	}

	public static int bytes2Int(byte[] buff) {
		//return (buff[0] << 24) + (buff[1] << 16) + (buff[2] << 8) + buff[3];		//错误，如果是负数时不对
		int mask = 0xff;
		int temp = 0;
		int n = 0;
		for (int i = 0; i < 4; i++) {
			n <<= 8;
			temp = buff[i] & mask;
			n |= temp;
		}
		return n;
	}

	public static int bytes2Int(byte[] buff, int srcPos) {
		//return (buff[srcPos] << 24) + (buff[srcPos + 1] << 16) + (buff[srcPos + 2] << 8) + buff[srcPos + 3];		//错误，如果是负数时不对
		int mask = 0xff;
		int temp = 0;
		int n = 0;
		for (int i = 0; i < 4; i++) {
			n <<= 8;
			temp = buff[srcPos + i] & mask;
			n |= temp;
		}
		return n;
	}

	public static void putInt(byte[] buff, int x, int desPos) {
		buff[desPos] = (byte) (x >> 24);
		buff[desPos + 1] = (byte) (x >> 16);
		buff[desPos + 2] = (byte) (x >> 8);
		buff[desPos + 3] = (byte) (x);
	}

}
